<?php

namespace App\Exceptions;

use App\Util\ResultsVo;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\URL;
use Illuminate\Validation\ValidationException;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Session\TokenMismatchException::class,
        \Illuminate\Validation\ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {

        $data = [];
        $data['code'] = 10000;
        $data['jump'] = URL::previous();

        switch ($exception) {
            case $exception instanceof ServiceException;//throw 异常

                $data['code'] = $exception->getCode();
                $data['message'] = $exception->getMessage();
                break;
            case $exception instanceof ValidationException;//DTO 验证失败
                $message = '';
                $msg = $exception->validator->getMessageBag()->toArray();
                foreach($msg as $key => $val) {
                    $item = Array();
                    $item['name'] = $key;
                    $item['message'] = implode(',',$val);
                    $data['errors'][] = $val;
                    $message .= $item['message'].',';
                    break;
                }
                $data['message'] = substr($message, 0, -1);
                break;
            case $exception instanceof AuthenticationException;//auth验证错误
                $data['code'] = 100007;
                $data['message'] = '登录后访问';
                break;
            case $exception instanceof UnauthorizedException;//sql错误
                $data['code'] = $exception->getStatusCode();
                $data['message'] = $exception->getMessage();
                break;
            case $exception instanceof \PDOException;//DTO 验证失败
                $data['message'] = $exception->getMessage();
                break;
            case $exception instanceof NotFoundHttpException;// 验证失败

                $data['message'] = '无效的路由';
                break;
            default:

                $data['message'] = '异常: 行:'.$exception->getLine().', File '.$exception->getFile().',Error '.$exception->getMessage();
                break;
        }


        if (strpos($request->path(), 'api/') !== false || $request->ajax()) {
            return response()->json(new ResultsVo($data));
        } else {
            if ($data['code'] == '100007') {
                if (strpos($request->path(), 'admin') !== false) {
                    $data['jump'] = '/admin/login';
                } else {
                    $data['jump'] = '/login';
                    return response()->view('www.prompt', ['data'=>$data]);
                }
            }
        }
        return response()->view('admin.prompt', ['data'=>$data]);
    }

    /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }
        return redirect()->guest('login');
    }
}
